import axios from 'axios'
import {createHashHistory} from 'history'

const history = createHashHistory()

const request = axios.create({
  baseURL: '/api/v1',
  timeout: 5000
})
// 设置token过期相关处理
axios.interceptors.request.use(function (config) {
  // 将token放入请求头
  const token = localStorage.getItem('token')
  if(token){
    config.headers['access_token'] = token
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  // token过期处理  401  token过期   402  (没有传token)
  if(response.data.code === '401' || response.data.code === '402'){
    // 重定向到登录页
    history.push('/login')
    history.go(0)
  }
  return response;
}, function (error) {
  return Promise.reject(error);
});

export default request